package codec

import (
	"database/sql"
	"fmt"

	"application/v3/internal/codec/js"
	"github.com/lib/pq/hstore"
)

// Type defines the codec type.
type Type string

// Available codec types.
const (
	None                = ""
	CayenneLPPType Type = "CAYENNE_LPP"
	CustomJSType   Type = "CUSTOM_JS"
)

// BinaryToJSON encodes the given binary payload to JSON.
func BinaryToJSON(t Type, fPort uint8, variables hstore.Hstore, decodeScript string, b []byte) ([]byte, error) {
	switch t {
	case CayenneLPPType:
		//return cayennelpp.BinaryToJSON(b)
		return nil, fmt.Errorf("do not support codec type: %s", t)
	case CustomJSType:
		return js.BinaryToJSON(fPort, GetVarsMap(variables.Map), decodeScript, b)
	default:
		return nil, fmt.Errorf("unknown codec type: %s", t)
	}
}

// JSONToBinary encodes the given JSON to binary.
func JSONToBinary(t Type, fPort uint8, variables hstore.Hstore, encodeScript string, jsonB []byte) ([]byte, error) {
	switch t {
	case CayenneLPPType:
		//return cayennelpp.JSONToBinary(jsonB)
		return nil, fmt.Errorf("do not support codec type: %s", t)
	case CustomJSType:
		return js.JSONToBinary(fPort, GetVarsMap(variables.Map), encodeScript, jsonB)
	default:
		return nil, fmt.Errorf("unknown codec type: %s", t)
	}
}

func GetVarsMap(varMap map[string]sql.NullString) map[string]string {
	vars := make(map[string]string)
	for k, v := range varMap {
		if v.Valid {
			vars[k] = v.String
		}
	}

	return vars
}
